# -*- coding:utf-8 -*-
from apscheduler.jobstores.base import JobLookupError
from fastapi import APIRouter
from Model.scheduler import schema
from Model.scheduler.tasks import run, scheduler

router = APIRouter()

@router.get("/job/jobs", response_model=schema.QueryResponse,
    summary='获取所有任务信息')
async def get_jobs(verbose: bool = False):
    """ 获取所有任务 """
    jobs = []
    try:
        job_list = scheduler.get_jobs()
        if job_list:
            jobs = [schema.Job(**task.__getstate__()) for task in job_list]

        if verbose:
            print(jobs)
    except Exception as e:
        print("错误",e)
        return schema.QueryResponse(
            message=f"Failed query {e.args}",
            status_code=0,
            jobs=jobs,
        )

    return schema.QueryResponse(
        message="Successfully query",
        status_code=1,
        jobs=jobs,
    )


@router.get("/job/{id}", response_model=schema.QueryResponse,
    summary='查询这个任务相信信息')
async def get_job_by_id(id: str, verbose: bool = False):
    """ 查询指定任务信息 """
    jobs = []
    try:
        job = scheduler.get_job(job_id=id)
        if job:
            jobs = [schema.Job(**job.__getstate__())]

        if verbose:
            print(job)
    except Exception as e:
        print(e)
        return schema.QueryResponse(
            message=f"Failed query {e.args}",
            status_code=0,
            jobs=jobs,
        )

    return schema.QueryResponse(
        message="Successfully query",
        status_code=1,
        jobs=jobs,
    )


@router.post("/job/interval", response_model=schema.OperateResponse,
    summary='添加任务')
async def add_job(res:schema.AddJob):
    """ 添加 job  根据指定秒来进行 """
    try:
        scheduler.add_job(
            id=res.id,        # id
            func=run, # 方法 # 如果要补存， 需要 去 tasks 添加你的方法
            kwargs={"type":res.func,"msg": res.msg, "verbose": res.verbose},
            trigger="interval",
            seconds=res.seconds,  # 循环间隔时间秒
            max_instances=10,
            **res.trigger_args,
        )
    except Exception as e:
        print("任务错误",e)
        return         schema.OperateResponse(
        message="Some internal error happened: {e.args}",
        status_code=0,
        type="add",
        )
    return schema.OperateResponse(
        message="Successfully add",
        status_code=1,
        type="add",
    )

@router.post("/job/reschedule"  ,summary='更新指定任务')
async def reschedule_job(res:schema.UpdateJob):
    """  更新Job """

    try:
        scheduler.reschedule_job(
            job_id=res.id,
            trigger="interval",
            seconds=res.seconds,  # 循环间隔时间秒
            **res.trigger_args
        )
    except Exception as e:
        print("任务错误",e)
        return         schema.OperateResponse(
        message="Some internal error happened: {e.args}",
        status_code=0,
        type="reschedule",
        )
    return schema.OperateResponse(
        message="Successfully reschedule",
        status_code=1,
        type="reschedule",
    )


@router.post("/job/pause",summary='暂停指定任务')
async def pause_job(rootkey: schema.RootKey):
    """pausing """

    try:
        scheduler.pause_job(job_id=rootkey.id)
    except Exception as e: 
        return schema.OperateResponse(
            message=f"Can't find <id:{id}> job",
            status_code=0,
            type="pause",
        )

    return schema.OperateResponse(
        message=f"Successfully pause <id:{id}> job",
        status_code=1,
        type="pause",
    )


@router.post("/job/resume",summary='恢复指定任务')
async def resume_job(rootkey: schema.RootKey):
    """resume pausing job by id"""
    try:
        scheduler.resume_job(job_id=rootkey.id)
    except Exception as e: 
        return schema.OperateResponse(
            message=f"Can't find <id:{id}> job",
            status_code=0,
            type="resume",
        )
    return schema.OperateResponse(
        message=f"Successfully resume <id:{id}> job",
        status_code=1,
        type="resume",
    )


@router.post("/job/delete/all",summary='删除所有任务')
async def delete_all_jobs():
    """delete all exist jobs"""

    try:
        scheduler.remove_all_jobs()
    except Exception:
        return schema.OperateResponse(
            message="there isn't any scheduled job",
            status_code=0,
            type="delete",
        )
    return schema.OperateResponse(
        message="Successfully delete all jobs",
        status_code=1,
        type="delete_all",
    )


@router.post("/job/delete",summary='删除指定任务')
async def delete_job(rootkey: schema.RootKey):
    """delete exist job by id"""
    try:
        scheduler.remove_job(job_id=rootkey.id)
    except JobLookupError:
        return schema.OperateResponse(
            message="failed delete",
            status_code=0,
            type="delete",
        )
    return schema.OperateResponse(
        message="Successfully delete",
        status_code=1,
        type="delete",
    )
